<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 前端用户登录/注册接口
 * @property User_mdl $users
 * @property Buy_lock_mdl $buyLock
 * @property Order_mdl $order 订单模型类
 * @property ApiOutput $apiOutput
 * @property Validation $validation 验证类
 * @property Tester_mdl $tester
 */
class Login extends CI_Controller {
	    
	public function __construct() {
		parent::__construct ();
		$this->load->model ( 'User_mdl', 'users' );
		$this->load->library('Validation','validation');
		// 登录注册前均需验证签名
		// 登录成功后才可以拿到cookie
		if( ! $this->validation->checkSign() ){
			$this->apiOutput->errorInput('签名无效');
		}
	}
	
	public function phone(){
	    // ==== 检查输入 ====
	    // 必须传入的参数
	    $must_provide_fields = array (
	        'phone',
	        'captcha',
	        'phoneID'
	    );
	    $input = check_input ( $_REQUEST, $must_provide_fields );
	    if (! $input) {
	        $this->apiOutput->errorInput();
	    }
	    if (! $input ['phone']) {
	        $this->apiOutput->error('手机号码格式不正确',-2);
	    }
	    $phone = $input['phone'];
	    $captcha = $input['captcha'];
	    $phoneID = $input['phoneID'];
	    $isReg = empty($input['isReg']) ? FALSE : TRUE;
	    // 非测试账号,需要验证手机验证码
	    // ==== 检查手机验证码 ====
	    $this->load->library ( 'PhoneCaptcha', NULL, 'captcha' );
	    if ( ! $this->isTester($phone, $captcha) && ! $this->captcha->check ( $phone,$captcha )) {
	        $this->apiOutput->error('验证码错误或失效',-3);
	    }
	    
	    // 检测该用户是否注册过
	    $where = array('phone'=>$phone);
	    $user = $this->users->findOne($where);
	    
	    if ( empty($user) ) {// 如果没有注册过：执行注册
	        $user = $this->users->create ();
	        $user->phone = $phone;
	        $user->phoneID = $phoneID;
	        $user->nickname = substr_replace ( $phone, '*****', 3, 5 );
	        $user->lastLoginPhoneID = $phoneID;
	        if( ! $user->reg() ){
	            // 保存到数据库失败:
	            $this->apiOutput->errorSystem();
	        }
	    }else{// 如果该手机号码已经注册
	        if($isReg){//如果是注册操作
	            $this->apiOutput->error('该手机号码注册,请直接登陆',-4);
	        }else{//否则执行登陆后操作
	        	// 检查是否为测试人员账号
	        	if( $user->isTest==1 ){
	        		$this->load->model('Tester_mdl','tester');
	        		$where = array();
	        		$where['userID'] = $user->id;
	        		$props = $this->tester->getOne($where);
	        		if( time() > $props['invalidTime'] ){
	        			$this->apiOutput->errorInput('账号已失效');
	        		}
	        	}
	            $this->afterLogin($user,$phoneID);
	        }
	    }
	    $this->apiOutput->put('user', $user->getBaseInfo())->out();
	}
	
	
	
	
	/**
	 * 微信登陆
	 */
	public function wechat() {
		$input = check_input ( $_REQUEST, array (
				'phoneID',//手机唯一标识
				'wxOpenID',//微信openID
				'nickname',//微信昵称
				'headImgUrl',//微信头像URL
				'wxUnionID',//微信unionID
		) );
		if (! $input) {
			$this->apiOutput->errorInput();
		}
		// 检查是否注册过
		$where = array('wxOpenID'=>$input['wxOpenID']);
		$user = $this->users->findOne($where);
		if (!empty($user)) {// 如果有注册过,执行登录检查
			$this->afterLogin($user,$input['phoneID']);
		}else {// 如果没有注册过,注册用户
			$user = $this->users->create();
			$user->phoneID = $input['phoneID'];
			$user->wxOpenID = $input['wxOpenID'];
			$user->nickname = $input['nickname'];
			$user->headImgUrl = $input['headImgUrl'];
			$user->wxUnionID = $input['wxUnionID'];
			$user->lastLoginPhoneID = $input['phoneID'];
			if( !$user->reg() ){
				$this->apiOutput->errorSystem();
			}
		}
		// 一切正常则输出用户信息
		$this->apiOutput->put('user', $user->getBaseInfo())->out();
	}
	/**
	 * 手机或微信登录时的检查操作
	 * @param UserORM $user 用户对象
	 */
	private function afterLogin($user,$phoneID){
// 		$this->load->model('Order_mdl','order');
// 		$unfinishOrders = $this->order->getUserUnfinishOrders($user->id);
// 		if( !empty($unfinishOrders) ){
// 			$this->apiOutput->error('您的账号正在其他设备上取水,请稍后再登陆',-99);
// 		}
		$user->afterLogin($phoneID);   
	}
	
	private function testLogin($phone,$captcha,$phoneID){
		$where['phone'] = $phone;
		$user = $this->users->findOne($where);
		if( empty($user) ){
			$this->apiOutput->errorInput('账号或密码不正确');
		}
		$this->load->model('Test_user_mdl','testUser');
		$where = array();
		$where['userID'] = $user->id;
		$props = $this->testUser->getOne($where);
		if( $props['password'] != $captcha ){
			$this->apiOutput->errorInput('账号或密码不正确');
		}
		if( time() > $props['invalidTime'] ){
			$this->apiOutput->errorInput('账号已失效');
		}
		
		$user->isTest = 1;
		$user->schoolID = $props['schoolID'];
		$this->afterLogin($user, $phoneID);
		$this->apiOutput->put('user', $user->getBaseInfo())->out();
		
	}
	
	public function isTester ($phone,$captcha){
		$phones = array('18826121780','13602417572');
		return $captcha==4738 && in_array($phone, $phones) ;
	}
	
	
	
	
}
